<template lang="pug">
  view
    view.status(v-if="showHeader"   :style="{ position: headerPosition, top: statusTop, opacity: afterHeaderOpacity }")
    view.header(v-if="showHeader"   :style="{ position: headerPosition, top: headerTop, opacity: afterHeaderOpacity }")
      view.addr
        view.icon.location
        text {{ city }}
    view.place(v-if="showHeader" )
    view.swiper
      view.swiper-box
        swiper(circular="true"  autoplay="true"  @change="swiperChange")
          swiper-item(v-for="swiper in swiperList"  :key="swiper.id")
            image(:src="`http://121.43.235.176/ShopMall/static/img/im/${swiper.img}`"  @tap="toSwiper(swiper)")
        view.indicator
          view.dots(v-for="(swiper, index) in swiperList"  :class="[currentSwiper >= index ? 'on' : '']"  :key="index")
    view.category-list
      view.category(v-for="(row, index) in categoryList"  :key="index"  @tap="toActivity(row)")
        view.img
          image(:src="`http://121.43.235.176/ShopMall/static/img/im/${row.img}`")
        view.text {{ row.name }}
    view.place(v-if="showHeader" )
    view.goods-list
      view.promotion
        view.text(style="color: #000000;float: left;width: 100%;line-height: 20upx;") 推荐商品
      view.product-list
        view.product(v-for="(nav, index) in productlist"  :key="index"  @tap="toGoods(nav)")
          image(:src="nav.pic + $pictureResolution(0, 375)"  webp)
          view.name {{ nav.name }}
          view.info
            view.price ¥{{ nav['price'] }}
</template>

<script>
var ttt = 0;
//高德SDK
import amap from '@/common/SDK/amap-wx.js';

export default {
  data() {
    return {
      lat: 0.0,
      lon: 0.0,
      salelist: [],
      productlist: [],
      catelist: [],
      showHeader: true,
      afterHeaderOpacity: 1, //不透明度
      headerPosition: 'fixed',
      headerTop: null,
      statusTop: null,
      nVueTitle: null,
      city: '北京',
      currentSwiper: 0,
      // 轮播图片
      swiperList: [
        {id: 1, src: 'url1', img: '1.jpg'},
        {id: 2, src: 'url2', img: '2.jpg'},
        {id: 3, src: 'url3', img: '3.jpg'},
        {id: 4, src: 'url4', img: '4.jpg'},
      ],
      // 分类菜单
      categoryList: [
        {id: 1, name: '精品推荐', img: '精品推荐.png'},
        {id: 2, name: '直供商品', img: '直供商品.png'},
        {id: 3, name: '热销排行', img: '热销.png'},
        {id: 4, name: '品购商品', img: '品购商品.png'}
      ],
      Promotion: [],
      //优惠券
      couponList: [
        {id: 1, name: '20元', price: 20, effdate: '2020-4-20至2020-4-28', coupontype: 0},
        {id: 2, name: '50元', price: 50, effdate: '2020-4-20至2020-4-28', coupontype: 0},
        {id: 3, name: '5折', price: 0.5, effdate: '2020-4-20至2020-4-28', coupontype: 1}
      ],
      //猜你喜欢列表
      productList: [],
      loadingText: '正在加载...'
    };
  },
  onPageScroll(e) {
    //兼容iOS端下拉时顶部漂移
    this.headerPosition = e.scrollTop >= 0 ? 'fixed' : 'absolute';
    this.headerTop = e.scrollTop >= 0 ? null : 0;
    this.statusTop = e.scrollTop >= 0 ? null : -this.statusHeight + 'px';
  },
  //下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
  onPullDownRefresh() {
    setTimeout(function () {

      uni.stopPullDownRefresh();
    }, 1000);
  },
  //上拉加载，需要自己在page.json文件中配置"onReachBottomDistance"
  onReachBottom() {
    return;
    //uni.showToast({ title: '触发上拉加载' });
    let len = this.productList.length;
    if (len >= 40) {
      this.loadingText = '到底了';
      return false;
    }
    // 演示,随机加入商品,生成环境请替换为ajax请求
    let end_goods_id = this.productList[len - 1].goods_id;
    for (let i = 1; i <= 10; i++) {
      let goods_id = end_goods_id + i;
      let p = {
        goods_id: goods_id,
        img: 'http://120.55.49.138/ShopMall/static/img/goods/p' + (goods_id % 10 == 0 ? 10 : goods_id % 10) + '.jpg',
        name: '商品名称商品名称商品名称商品名称商品名称',
        price: '￥168',
        slogan: '1235人付款'
      };
      this.productList.push(p);
    }
  },
  onLoad() {
    // if (this.sessionid == null || this.sessionid == '') {
    // 	uni.showToast({title: "请先登录！"});
    // 	uni.navigateTo({
    // 		url: '../login/login'
    // 	});
    // 	//return;
    // }

    uni.getLocation({
      type: 'wgs84',
      success: function (res) {
        uni.setStorageSync("lat", res.longitude);
        uni.setStorageSync("lon", res.latitude);
        console.log('当前位置的经度：' + res.longitude);
        console.log('当前位置的纬度：' + res.latitude);
      }
    });
    // #ifdef APP-PLUS
    this.nVueTitle = uni.getSubNVueById('homeTitleNvue');
    this.nVueTitle.onMessage(res => {
      let type = res.data.type;
      if (type == 'focus') {
        this.toSearch();
      }
    });
    this.showHeader = false;
    this.statusHeight = plus.navigator.getStatusbarHeight();
    // #endif
    this.amapPlugin = new amap.AMapWX({
      //高德地图KEY，随时失效，请务必替换为自己的KEY，参考：http://ask.dcloud.net.cn/article/35070
      key: '73057bd9fd260b392db6a203d6cb5943'
    });
    //定位地址
    this.amapPlugin.getRegeo({
      success: data => {
        this.loadData();
        console.log(data[0].regeocodeData.addressComponent);
        if (typeof (data[0].regeocodeData.addressComponent.city) == "string")
          this.city = data[0].regeocodeData.addressComponent.city.replace(/市/g, ''); //把"市"去掉
        else
          this.city = data[0].regeocodeData.addressComponent.province.replace(/市/g, '');
        // #ifdef APP-PLUS
        this.nVueTitle.postMessage({type: 'location', city: this.city});
        // #endif
      }
    });


  },
  methods: {
    loadData: function () {
      //开启定时器
      //this.Timer();
      //加载活动专区
      //this.loadPromotion();
      this.loadCouponList();
      this.loadSaleList();
      this.loadProductList();
      this.loadCatelist();
    },

    loadCouponList: function () {
      //var indexNav = this.$SysCache.get("app_index_couponlist");
      var indexNav = false;
      if (indexNav) {
        this.couponList = indexNav;
      } else {
        // this.$Request.get(this.$api.coupon.list).then(res => {
        //
        // 	if (res.code == 200) {
        // 		this.couponList = res.data;
        // 		this.$SysCache.put("app_index_couponlist",res.data,86400);
        // 	}
        // })
      }
    },

    loadSaleList: function () {
      //var indexNav = this.$SysCache.get("app_index_salelist");
      var indexNav = false;
      if (indexNav) {
        this.salelist = indexNav;
      } else {
        var lat = uni.getStorageSync("lat");
        var lon = uni.getStorageSync("lon");
        console.log("lat:" + lat);
        console.log("lon:" + lon);
        this.$Request.get(this.$api.product.list + '?productType=1&latitude=' + lat + '&longitude=' + lon).then(res => {

          if (res.code == 200) {
            this.salelist = res.data.list;
            this.$SysCache.put('app_index_salelist', res.data, 86400);
          }
        });
      }
    },
    loadProductList: function () {
      //var indexNav = this.$SysCache.get("app_index_productlist");
      var indexNav = false;
      if (indexNav) {
        this.productlist = indexNav;
      } else {
        var lat = uni.getStorageSync("lat");
        var lon = uni.getStorageSync("lon");
        console.log("lat:" + lat);
        console.log("lon:" + lon);
        this.$Request.get(this.$api.product.list + '?promotion_status=3&latitude=' + lat + '&longitude=' + lon).then(res => {

          if (res.code == 200) {
            this.productlist = res.data.list;
            this.$SysCache.put('app_index_productlist', res.data, 86400);
          }
        });
      }
    },
    loadCatelist: function () {
      this.$Request.get(this.$api.home.category).then(res => {
        if (res.code == 200) {
          //
          this.catelist = res.data;
        }
      });
    },

    //加载Promotion 并设定倒计时,,实际应用中应该是ajax加载此数据。
    loadPromotion() {
      let cutTime = new Date();
      let yy = cutTime.getFullYear(),
          mm = cutTime.getMonth() + 1,
          dd = cutTime.getDate();
      let tmpcountdown = yy + '/' + mm + '/' + dd + ' 23:59:59';
      let tmpPromotion = [
        {
          title: '整点秒杀',
          ad: '整天秒杀专区',
          img: 'http://120.55.49.138/ShopMall/static/img/s1.jpg',
          countdown: false
        },
        {
          title: '限时抢购',
          ad: '每天23点上线',
          img: 'http://120.55.49.138/ShopMall/static/img/s2.jpg',
          countdown: tmpcountdown
        } //countdown为目标时间，程序会获取当前时间倒数
      ];
      //检查倒计时
      for (let i = 0; i < tmpPromotion.length; i++) {
        let row = tmpPromotion[i];
        if (row.countdown) {
          let h = '00',
              m = '00',
              s = '00';
          let currentTime = new Date();
          let cutoffTime = new Date(tmpcountdown);
          if (!(currentTime >= cutoffTime)) {
            let countTime = parseInt((cutoffTime.getTime() - currentTime.getTime()) / 1000);
            h = parseInt(countTime / 3600);
            m = parseInt((countTime % 3600) / 60);
            s = countTime % 60;
            h = h < 10 ? '0' + h : h;
            m = m < 10 ? '0' + m : m;
            s = s < 10 ? '0' + s : s;
          }
          tmpPromotion[i].countdown = {h: h, m: m, s: s};
        }
      }
      this.Promotion = tmpPromotion;
    },
    //定时器
    Timer() {
      setInterval(() => {
        if (this.Promotion.length > 0) {
          for (let i = 0; i < this.Promotion.length; i++) {
            let row = this.Promotion[i];
            if (row.countdown) {
              if (!(row.countdown.h == 0 && row.countdown.m == 0 && row.countdown.s == 0)) {
                if (row.countdown.s > 0) {
                  row.countdown.s--;
                  row.countdown.s = row.countdown.s < 10 ? '0' + row.countdown.s : row.countdown.s;
                } else if (row.countdown.m > 0) {
                  row.countdown.m--;
                  row.countdown.m = row.countdown.m < 10 ? '0' + row.countdown.m : row.countdown.m;
                  row.countdown.s = 59;
                } else if (row.countdown.h > 0) {
                  row.countdown.h--;
                  row.countdown.h = row.countdown.h < 10 ? '0' + row.countdown.h : row.countdown.h;
                  row.countdown.m = 59;
                  row.countdown.s = 59;
                }
                this.Promotion[i].countdown = row.countdown;
              }
            }
          }
        }
      }, 1000);
    },
    //消息列表
    toMsg() {
      uni.navigateTo({
        url: '../../msg/msg'
      });
    },
    //搜索跳转
    toSearch() {
      uni.navigateTo({
        url: '../../search/index'
      });
    },
    toNavList: function (url, title) {
      // uni.showToast({
      // 	title: url,
      // 	mask: false,
      // 	duration: 1500,
      // 	icon: "none"
      // });
      uni.navigateTo({
        url: url
      });
    },
    //轮播图跳转
    toSwiper(e) {
      uni.showToast({title: e.src, icon: 'none'});
    },
    //活动跳转
    toActivity(e) {
      //uni.showToast({title: e.name,icon:"none"});
      uni.setStorageSync('catName', e.name);
      uni.navigateTo({
        url: '../../goods/goods-list/goods-list-distance?cid=' + e.id + '&name=' + e.name
      });
    },
    //分类跳转
    toCategory(e) {
      //uni.showToast({title: e.name,icon:"none"});
      uni.setStorageSync('catName', e.name);
      uni.navigateTo({
        url: '../../goods/goods-list/goods-list?cid=' + e.id + '&name=' + e.name
      });
    },
    //推荐商品跳转
    toPromotion(e) {
      uni.showToast({title: e.title, icon: 'none'});
    },
    toFreeGoods(e) {
      //uni.showToast({ title: '商品' + e.id, icon: 'none' });
      uni.navigateTo({
        url: '../../goods/goods?cid=' + e.id + '&free=1' + "&shopId=" + e.shopId
      });
    },
    //商品跳转
    toGoods(e) {
      //uni.showToast({ title: '商品' + e.id, icon: 'none' });
      uni.navigateTo({
        url: '../../goods/goods?cid=' + e.id + "&shopId=" + e.shopId
      });
    },
    //轮播图指示器
    swiperChange(event) {
      this.currentSwiper = event.detail.current;
    }
  }
};
</script>
<style lang="scss">
@import "./home";
</style>
